import util from "@/libs/util";
import api from "@/api";
import { Message } from "element-ui";

export default {
  namespaced: true,
  state: {
    cartlist: util.store.getItem("cartlist"),
    cartselect: [],
    cart_goods_num: 0,
  },
  /**
   * actions 通过 this.$store.dispatch 来调用
   * 可以异步请求，放置一些业务代码
   */
  actions: {
    /**
     * 初始化购物车数据
     * @param {*} param0
     */
    async init({ state }) {
      let result = await api.MY_CAR();
      state.cartlist = result || [];

      let cartselect = [];
      result.forEach((item) => {
        cartselect.push({
          goods: new Array(item.good.length),
        });
      });

      state.cartselect = cartselect;
    },
    /**
     * 添加购物车
     * @param {*} param0
     * @param {*} data
     */
    async add(state, data) {
      await api.ADD_TO_CAR(data);
      await this.dispatch("car/init");
    },

    async removeGoods({ state }, { index, i }) {
      let good = state.cartlist[index].good[i];
      await api.CAR_DEL(good.cart_id).then(() => {
        Message.success("操作成功");
      });
      await this.dispatch("car/init");
    },
  },
  /**
   * mutations 通过 this.$store.commit 来调用
   * 专注于修改 state 不能异步 state相关的操作尽量在 mutations中完成
   */
  mutations: {
    /**
     * @description 设置数据
     * @param {Object} state
     * @param {*} info info
     */
    set(state, info) {
      util.store.setItem("cartlist", info);
      state.cartlist = info;
    },
    /**
     * 商品选中
     * @param {*} state
     * @param {*} index
     * @param {*} i
     */
    goodsSelect(state, { index, i }) {
      let cartselect = state.cartselect;
      cartselect[index].goods[i] = !cartselect[index].goods[i];
      state.cartselect = cartselect;
    },
    /**
     * 店铺选中
     * @param {*} state
     * @param {*} index
     * @param {*} i
     */
    shopSelect(state, { index, select }) {
      console.log(index, select);
      let cartselect = state.cartselect;
      for (let i = 0; i < cartselect[index].goods.length; i++) {
        cartselect[index].goods[i] = select;
      }
      console.log(cartselect[index].goods);
      state.cartselect = cartselect;
    },
    allShopSelect(state, status) {
      let cartselect = state.cartselect;
      cartselect.forEach((item, index) => {
        for (let i = 0; i < cartselect[index].goods.length; i++) {
          cartselect[index].goods[i] = status;
        }
      });
      state.cartselect = cartselect;
    },
  },
};
